package com.rc.web.listener;


import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DialectFactory;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.tenant.TenantFactory;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.rc.common.model.BaseConEntity;
import com.rc.common.model.BaseImgEntity;
import com.rc.common.model.BaseUserEntity;
import com.rc.pojo.po.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.rc.common.constant.RoleEnum.ADMIN;

/**
 * MyBatis-Flex 配置类
 * 用于配置全局监听器、方言和租户工厂
 */
@Configuration
public class FlexConfig implements ConfigurationCustomizer {

    public FlexConfig(){
        // 注册插入监听器
        FlexGlobalConfig.getDefaultConfig().registerInsertListener(new BaseInsertListener(), BaseConEntity.class,BaseUserEntity.class, BaseImgEntity.class);
        // 注册更新监听器
        FlexGlobalConfig.getDefaultConfig().registerUpdateListener(new BaseUpdateListener(), BaseUserEntity.class);
        // 注册达梦数据库方言
        DialectFactory.registerDialect(DbType.DM,new MyDmDialect());
        // 设置默认数据库类型为达梦
        FlexGlobalConfig.getDefaultConfig().setDbType(DbType.DM);
    }

    /**
     * 创建租户工厂Bean
     * @return 租户工厂实例
     */
    @Bean
    public TenantFactory tenantFactory(){
        return new TenantFactory() {
            @Override
            public Object[] getTenantIds(String tableName) {
                return TenantFactory.super.getTenantIds(tableName);
            }

            @Override
            public Object[] getTenantIds() {
                // 从会话中获取当前用户
                User user = StpUtil.getSession().getModel("user", User.class);

                // 游客：使用登录ID作为租户ID
                if (user == null){
                    long loginIdAsLong = StpUtil.getLoginIdAsLong();
                    return new Object[]{loginIdAsLong};
                }

                // 管理员：忽略租户条件
                if (ADMIN == user.getRole()){
                    return null;
                }

                // 农场管理员和员工：使用农场ID作为租户ID
                return new Object[]{user.getFarmId()};
            }
        };
    }

    @Override
    public void customize(FlexConfiguration flexConfiguration) {
        // 自定义MyBatis-Flex配置
    }
}
